<template>
  <div class="personal-info-container">
    <el-card class="info-card">
      <div slot="header" class="card-header">
        <span>个人信息</span>
        <el-button
            type="primary"
            icon="el-icon-edit"
            @click="isEdit = !isEdit"
        >
          {{ isEdit ? '保存' : '编辑' }}
        </el-button>
      </div>
      <el-form
          ref="infoForm"
          :model="form"
          label-width="120px"
          :disabled="!isEdit"
      >

        <el-form-item label="头像" prop="profileSrc">
          <el-upload
              class="avatar-uploader"
              action="api/uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
              :disabled="!isEdit"
          >
            <img v-if="form.profileSrc" :src="form.profileSrc"  class="avatar" />
            <i v-else class="el-icon-user avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="form.uid" disabled />
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="form.creatTime" disabled />
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>

export default {
  name: 'Profile',
  data() {
    return {
      isEdit: false, // 编辑状态标识
      originalProfileSrc: '',
      uploadProgress: 0,
      uploadProgressShow: false,
      form: {
        uid: '',
        username: '',
        email: '',
        phone: '',
        sex: '',
        creatTime: '',
        profileSrc: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchPersonalInfo()
  },
  methods: {
    // 获取个人信息
    async fetchPersonalInfo() {
        this.$http.get('/api/getUserInfo',{params: {username:localStorage.getItem('user')}})
            .then(res=>{
              this.form = { ...res.data.data }
              if (res.data.code === 400){
                this.$message.error("获取个人信息失败");
              }
            })
            .catch(error=>{
              this.$message.error("获取个人信息失败");
            })
    },
    // 保存编辑后的个人信息
    async handleSave() {
      const valid = await this.$refs.infoForm.validate()
      if (!valid) return
      this.$http.post('/api/updateUserInfo', this.form)
          .then(res=>{
            this.$message.success("更新个人信息成功");
            this.isEdit = false
          })
          .catch(error=>{
            this.$message.error("更新个人信息失败");
          })
    },
    // 头像上传成功回调
    handleAvatarSuccess(res, file, fileList) {
      if (res.code === 200) {
        this.form.profileSrc = res.data;
        console.log(res.data);
        URL.revokeObjectURL(URL.createObjectURL(file.raw));
        this.uploadProgressShow = false;
        this.$message.success('头像上传成功');
      } else {
        this.$message.error('头像上传失败：' + res.msg);
        if (this.originalProfileSrc) {
          this.form.profileSrc = this.originalProfileSrc;
        }
      }
    },
    handleAvatarError(err, file, fileList) {
      this.$message.error('头像上传失败，网络或服务端异常');
      if (this.originalProfileSrc) {
        this.form.profileSrc = this.originalProfileSrc;
      }
      this.uploadProgressShow = false;
    },
    // 头像上传前校验
    beforeAvatarUpload(file) {
      this.originalProfileSrc = this.form.profileSrc; // 保存当前头像地址
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  },
  watch: {
    isEdit(newVal) {
      if (newVal) {
      } else {
        this.handleSave()
      }
    }
  }
}
</script>

<style scoped>
.personal-info-container {
  padding: 20px;
}
.info-card {
  width: 600px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}
.info-card:hover {
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebf2f9;
}

/* 头像区域样式 */
.avatar-uploader {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
.avatar-wrapper {
  position: relative;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  background: #f0f5ff;
  transition: all 0.3s ease;
}
.avatar-wrapper:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
}

/* 头像图片样式 */
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.5s ease;
}
.avatar:hover {
  transform: scale(1.05);
}

/* 占位符样式（无头像时） */
.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #409eff;
}
.avatar-icon {
  font-size: 32px;
  margin-bottom: 8px;
  opacity: 0.7;
}
.placeholder-text {
  font-size: 14px;
  color: #6b7785;
}

/* 上传交互效果 */
.el-upload:hover .avatar-wrapper {
  box-shadow: 0 0 0 2px #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-card {
    width: 90%;
    max-width: 500px;
  }
  .avatar-wrapper {
    width: 100px;
    height: 100px;
  }
  .avatar-icon {
    font-size: 36px;
  }
}

/* 头像区域优化样式（缩小尺寸版） */
.avatar-uploader {
  margin-bottom: 16px;
}
.avatar-wrapper {
  width: 80px;
  height: 80px;
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.2);
  background: linear-gradient(135deg, #f5f9ff, #e8f0fe);
}
.avatar-wrapper:hover {
  transform: translateY(-5px) scale(1.05);
  box-shadow: 0 8px 28px rgba(64, 158, 255, 0.3);
}
.avatar-wrapper::before {
  top: -8px;
  left: -8px;
  right: -8px;
  bottom: -8px;
}

/* 头像图片样式 */
.avatar {
  transition: transform 0.4s ease;
}
.avatar:hover {
  transform: scale(1.08);
}

/* 占位符样式 */
.avatar-icon {
  font-size: 32px;
  margin-bottom: 8px;
}
.placeholder-text {
  font-size: 12px;
}

/* 上传交互效果 */
.el-upload:hover .avatar-wrapper {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
}

/* 加载状态指示器 */
.upload-progress-overlay {
  width: 80px;
  height: 80px;
}
.progress-circle {
  width: 40px;
  height: 40px;
  border-width: 3px;
}

/* 响应式设计（移动端进一步缩小） */
@media (max-width: 768px) {
  .avatar-wrapper {
    width: 70px;
    height: 70px;
  }
  .avatar-icon {
    font-size: 28px;
  }
  .upload-progress-overlay {
    width: 70px;
    height: 70px;
  }
  .progress-circle {
    width: 35px;
    height: 35px;
  }
}
</style>